<template>
	<view class="container">
		<view class="page-title">撮合中心</view>
		
		<!-- Tab切换：我是买家 / 我是卖家 -->
		<view class="tab-bar">
			<view class="tab-item" :class="{ active: currentTab === 'buyer' }" @click="switchTab('buyer')">
				我是买家
			</view>
			<view class="tab-item" :class="{ active: currentTab === 'seller' }" @click="switchTab('seller')">
				我是卖家
			</view>
		</view>
		
		<!-- 买家视角：查看撮合进度 -->
		<view v-if="currentTab === 'buyer'">
			<view class="query-section">
				<view class="input-label">查询撮合进度</view>
				<view class="query-row">
					<input class="query-input" 
						   v-model="demandId" 
						   placeholder="请输入需求ID" 
						   type="number" />
					<button class="btn-primary query-btn" @click="queryBuyerMatches">查询</button>
				</view>
			</view>
			
			<scroll-view class="scroll-area" scroll-y="true">
				<view v-for="item in buyerMatchList" :key="item.id" class="list-item">
					<view class="match-header">
						<text class="match-title">撮合记录 #{{ item.id }}</text>
						<view class="match-status" :class="getStatusClass(item.status)">
							{{ getMatchStatusText(item.status) }}
						</view>
					</view>
					
					<view class="match-content">
						<text class="match-info">需求ID：{{ item.demandId }}</text>
						<text class="match-info">卖家ID：{{ item.sellerId }}</text>
						<text class="match-info">创建时间：{{ item.createTime }}</text>
						<text v-if="item.updateTime" class="match-info">更新时间：{{ item.updateTime }}</text>
					</view>
					
					<view v-if="item.remark" class="match-remark">
						<text class="remark-label">备注：</text>
						<text class="remark-content">{{ item.remark }}</text>
					</view>
				</view>
				
				<view v-if="buyerMatchList.length === 0 && !loading" class="empty-tip">
					请输入需求ID查询撮合进度
				</view>
			</scroll-view>
		</view>
		
		<!-- 卖家视角：查看撮合线索并处理 -->
		<view v-if="currentTab === 'seller'">
			<scroll-view class="scroll-area" 
						 scroll-y="true" 
						 @scrolltolower="loadMoreSellerMatches"
						 refresher-enabled="true"
						 @refresherrefresh="refreshSellerMatches"
						 :refresher-triggered="refreshing">
				<view v-for="item in sellerMatchList" :key="item.id" class="list-item">
					<view class="match-header">
						<text class="match-title">撮合线索 #{{ item.id }}</text>
						<view class="match-status" :class="getStatusClass(item.status)">
							{{ getMatchStatusText(item.status) }}
						</view>
					</view>
					
					<view class="match-content">
						<text class="match-info">需求ID：{{ item.demandId }}</text>
						<text class="match-info">买家需求：{{ item.demandDescription }}</text>
						<text class="match-info">需求量：{{ item.quantity }} {{ item.quantityUnit }}</text>
						<text class="match-info">创建时间：{{ item.createTime }}</text>
					</view>
					
					<view v-if="item.contactInfo" class="contact-info">
						<text class="contact-label">买家联系方式：</text>
						<text class="contact-content">{{ item.contactInfo }}</text>
					</view>
					
					<!-- 卖家操作按钮 -->
					<view v-if="item.status === 2" class="match-actions">
						<button class="btn-success action-btn" @click="sellerDecision(item, 1)">我有货</button>
						<button class="btn-danger action-btn" @click="sellerDecision(item, 3)">没货</button>
					</view>
					
					<view v-if="item.remark" class="match-remark">
						<text class="remark-label">备注：</text>
						<text class="remark-content">{{ item.remark }}</text>
					</view>
				</view>
				
				<view v-if="sellerMatchList.length === 0 && !loading" class="empty-tip">
					暂无撮合线索
				</view>
				
				<view v-if="loading" class="loading-tip">
					加载中...
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
import { api } from '../../utils/request.js';
import authStore from '../../store/auth.js';

export default {
	data() {
		return {
			// 当前tab: buyer(买家) / seller(卖家)
			currentTab: 'buyer',
			
			// 买家查询参数
			demandId: '',
			
			// 买家撮合列表
			buyerMatchList: [],
			
			// 卖家撮合列表
			sellerMatchList: [],
			sellerPageNo: 1,
			sellerHasMore: true,
			
			// 加载状态
			loading: false,
			refreshing: false,
			
			// 当前用户
			currentUser: null
		}
	},
	
	onLoad(options) {
		// 撮合中心页面：买家查看撮合进度，卖家查看线索并决策
		// 买家接口：GET /api/match/buyer/list
		// 卖家接口：GET /api/match/seller/list 和 POST /api/match/seller/decision
		
		// 检查URL参数
		if (options.demandId) {
			this.demandId = options.demandId;
		}
		if (options.type) {
			this.currentTab = options.type;
		}
		
		this.checkAuth();
	},
	
	onShow() {
		// 每次显示页面时刷新数据
		if (authStore.isLoggedIn()) {
			this.refreshCurrentTab();
		}
	},
	
	methods: {
		// 检查登录状态
		async checkAuth() {
			if (!authStore.isLoggedIn()) {
				try {
					await authStore.loginWithWeixin();
					this.currentUser = authStore.getCurrentUser();
					this.initData();
				} catch (error) {
					uni.showModal({
						title: '提示',
						content: '需要登录后才能查看撮合信息',
						success: (res) => {
							if (res.confirm) {
								uni.switchTab({ url: '/pages/user/index' });
							} else {
								uni.navigateBack();
							}
						}
					});
				}
			} else {
				this.currentUser = authStore.getCurrentUser();
				this.initData();
			}
		},
		
		// 初始化数据
		initData() {
			if (this.currentTab === 'buyer' && this.demandId) {
				this.queryBuyerMatches();
			} else if (this.currentTab === 'seller') {
				this.loadSellerMatchList();
			}
		},
		
		// 切换tab
		switchTab(tab) {
			if (this.currentTab === tab) return;
			
			this.currentTab = tab;
			if (tab === 'seller') {
				if (this.sellerMatchList.length === 0) {
					this.loadSellerMatchList();
				}
			}
		},
		
		// 刷新当前tab数据
		refreshCurrentTab() {
			if (this.currentTab === 'buyer' && this.demandId) {
				this.queryBuyerMatches();
			} else if (this.currentTab === 'seller') {
				this.refreshSellerMatches();
			}
		},
		
		// 买家查询撮合进度
		async queryBuyerMatches() {
			if (!this.demandId) {
				uni.showToast({
					title: '请输入需求ID',
					icon: 'none'
				});
				return;
			}
			
			this.loading = true;
			
			try {
				const response = await api.get('/api/match/buyer/list', {
					demandId: this.demandId
				}, true);
				
				this.buyerMatchList = response.list || response || [];
				
			} catch (error) {
				console.error('查询买家撮合失败:', error);
				this.buyerMatchList = [];
			} finally {
				this.loading = false;
			}
		},
		
		// 加载卖家撮合列表
		async loadSellerMatchList(isRefresh = false) {
			if (this.loading) return;
			if (!isRefresh && !this.sellerHasMore) return;
			
			// 获取当前用户的sellerId，这里假设用户信息中有sellerId字段
			// 实际应用中需要根据后端用户结构调整
			const sellerId = this.currentUser?.id || this.currentUser?.sellerId;
			if (!sellerId) {
				uni.showToast({
					title: '获取卖家信息失败',
					icon: 'none'
				});
				return;
			}
			
			this.loading = true;
			
			try {
				const pageNo = isRefresh ? 1 : this.sellerPageNo;
				const response = await api.get('/api/match/seller/list', {
					sellerId: sellerId,
					pageNo: pageNo,
					pageSize: 10
				}, true);
				
				const { list, total } = response;
				
				if (isRefresh) {
					this.sellerMatchList = list || [];
					this.sellerPageNo = 1;
				} else {
					this.sellerMatchList = this.sellerMatchList.concat(list || []);
				}
				
				// 判断是否还有更多数据
				this.sellerHasMore = this.sellerMatchList.length < total;
				if (!isRefresh) {
					this.sellerPageNo++;
				}
				
			} catch (error) {
				console.error('加载卖家撮合列表失败:', error);
			} finally {
				this.loading = false;
				this.refreshing = false;
			}
		},
		
		// 下拉刷新卖家撮合
		refreshSellerMatches() {
			this.refreshing = true;
			this.sellerHasMore = true;
			this.loadSellerMatchList(true);
		},
		
		// 上拉加载更多卖家撮合
		loadMoreSellerMatches() {
			this.loadSellerMatchList(false);
		},
		
		// 卖家决策
		async sellerDecision(matchRecord, status) {
			const statusText = status === 1 ? '接单' : '拒单';
			
			uni.showModal({
				title: '确认操作',
				content: `确定要${statusText}这个撮合吗？`,
				success: async (res) => {
					if (res.confirm) {
						try {
							await api.post('/api/match/seller/decision', {
								id: matchRecord.id,
								status: status
							}, true);
							
							uni.showToast({
								title: `${statusText}成功`,
								icon: 'success'
							});
							
							// 刷新列表
							this.refreshSellerMatches();
							
						} catch (error) {
							console.error('卖家决策失败:', error);
						}
					}
				}
			});
		},
		
		// 获取撮合状态文本
		getMatchStatusText(status) {
			const statusMap = {
				1: '已接单',
				2: '待处理',
				3: '已拒绝',
				4: '已完成'
			};
			return statusMap[status] || '未知状态';
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			const classMap = {
				1: 'status-accepted',
				2: 'status-pending',
				3: 'status-rejected',
				4: 'status-completed'
			};
			return classMap[status] || '';
		}
	}
}
</script>

<style scoped>
.query-section {
	background: white;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.query-row {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.query-input {
	flex: 1;
	border: 2rpx solid #e1e1e1;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
}

.query-btn {
	padding: 20rpx 40rpx;
	font-size: 28rpx;
}

.scroll-area {
	height: calc(100vh - 280rpx);
}

.match-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.match-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
}

.match-status {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	color: white;
}

.status-pending {
	background-color: #ff9500;
}

.status-accepted {
	background-color: #4cd964;
}

.status-rejected {
	background-color: #ff3b30;
}

.status-completed {
	background-color: #007aff;
}

.match-content {
	margin-bottom: 20rpx;
}

.match-info {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.contact-info {
	background: #f8f8f8;
	padding: 20rpx;
	border-radius: 8rpx;
	margin-bottom: 20rpx;
}

.contact-label {
	font-size: 26rpx;
	color: #999;
}

.contact-content {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.match-actions {
	display: flex;
	gap: 20rpx;
	justify-content: flex-end;
	margin-bottom: 20rpx;
}

.action-btn {
	padding: 15rpx 30rpx;
	font-size: 26rpx;
	border-radius: 6rpx;
	border: none;
}

.match-remark {
	background: #f0f0f0;
	padding: 20rpx;
	border-radius: 8rpx;
}

.remark-label {
	font-size: 26rpx;
	color: #999;
}

.remark-content {
	font-size: 28rpx;
	color: #333;
}

.empty-tip {
	text-align: center;
	color: #999;
	padding: 60rpx 0;
	font-size: 28rpx;
}

.loading-tip {
	text-align: center;
	color: #666;
	padding: 30rpx 0;
	font-size: 28rpx;
}
</style>